import { api } from '@/utils/request'

const state = {
  events: []
}

const mutations = {
  SET_EVENTS(state, events) {
    state.events = events
  }
}

const actions = {
  // 获取即将到来的事件
  async fetchUpcomingEvents({ commit }, params = { limit: 10 }) {
    try {
      const response = await api.get('/calendar/upcoming', params)
      commit('SET_EVENTS', response.data || [])
      return response.data
    } catch (error) {
      console.error('获取日历事件失败:', error)
      throw error
    }
  },

  // getUpcomingEvents 作为 fetchUpcomingEvents 的别名, 保持兼容性
  async getUpcomingEvents({ dispatch }, params) {
    return dispatch('fetchUpcomingEvents', params)
  },
  
  async createEvent({ commit }, eventData) {
    try {
        const response = await api.post('/calendar/create', eventData);
        // We can optionally add the new event to the state
        // commit('ADD_EVENT', response.data); 
        return response.data;
    } catch (error) {
        console.error('创建事件失败:', error);
        throw error;
    }
  },

  // 获取事件详情
  async getEventDetail({ commit }, eventId) {
    try {
      console.log('Requesting event detail for ID:', eventId)
      const response = await api.get(`/calendar/event/${eventId}`)
      console.log('Event detail response:', response)
      return response.data
    } catch (error) {
      console.error('获取事件详情失败:', error)
      throw error
    }
  },

  // 更新事件
  async updateEvent({ commit }, { eventId, eventData }) {
    try {
      console.log('Updating event:', eventId, eventData)
      const response = await api.put(`/calendar/event/${eventId}`, eventData)
      return response.data
    } catch (error) {
      console.error('更新事件失败:', error)
      throw error
    }
  },

  // 删除事件
  async deleteEvent({ commit }, eventId) {
    try {
      const response = await api.delete(`/calendar/event/${eventId}`)
      return response.data
    } catch (error) {
      console.error('删除事件失败:', error)
      throw error
    }
  }
}

const getters = {
  events: state => state.events
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
} 